/*
 * NodeSequence.cpp
 *
 *  Created on: 2009-11-13
 *      Author: ws
 */

#include"Node.hpp"
#include"NodeSequence.hpp"

NodeSequence::iterator  NodeSequence::iterator::operator ++(int)
{
	Node* x= ptr;
	ptr = ptr->next;
	return iterator(x);
}

NodeSequence::iterator& NodeSequence::iterator::operator ++()
{
	ptr = ptr->next;
	return *this;
}

NodeSequence::iterator NodeSequence::iterator::operator --(int)
{
	Node * x = ptr;
	ptr = ptr->prev;
	return iterator(x);
}

NodeSequence::iterator& NodeSequence::iterator::operator -- ()
{
	ptr = ptr->prev;
	return *this;
}

NodeSequence::iterator NodeSequence::iterator::operator + (int count)
{
	Node * x = ptr;
	for(int i = 0 ; i < count; i++)
	{
		x = x->next;
	}
	return iterator(x);
}

NodeSequence::iterator NodeSequence::iterator::operator -(int count)
{
	Node *x = ptr;
	for(int i = 0; i < count; i++)
	{
		x = x->prev;
	}
	return iterator(x);
}

NodeSequence::NodeSequence()
{
	_size = 0; 
	header = reinterpret_cast<Node*>(new _intrusive_node);
	header->next = header;
	header->prev = header;
}

NodeSequence::~NodeSequence()
{
	Node *n = header->next;
	while(n != header)
	{
		Node * next = n->next;
		delete n;
		n = next;
	}
	_intrusive_node * in = reinterpret_cast<_intrusive_node*>(header);
	delete in;
}

NodeSequence::iterator NodeSequence::begin()const
{
	return iterator(header->next);
}

NodeSequence::iterator NodeSequence::end()const
{
	return iterator(header);
}

void NodeSequence::push_back(Node *n)
{
	_size++;
	header->prev->next = n;
	n->prev = header->prev;
	header->prev = n;
	n->next = header;
}

void NodeSequence::push_front(Node* n)
{
	_size++;
	n->next = header->next;
	header->next = n;
	n->next->prev = n;
	n->prev = header;
}

//insert the node n before the pos
NodeSequence::iterator NodeSequence::insert(NodeSequence::iterator & pos, Node *n)
{
	_size++;
	Node* prev = pos->prev;

	n->prev = prev;
	prev->next = n;

	n->next = pos.ptr;
	pos->prev = n;
	return iterator(n);
}

//remove the node in the pos and pos is set to next postion
Node * NodeSequence::remove(NodeSequence::iterator& pos)
{
	_size--;
	Node * n = pos.ptr;
	n->prev->next = n->next;
	n->next->prev = n->prev;
	pos.ptr = n->next;
	n->prev = NULL;
	n->next = NULL;
	return n;	
}



